package com.yzcrm.erp.crm.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.TxSerializable;
import com.yzcrm.common.config.exception.YzcrmException;
import com.yzcrm.common.config.paragetter.BasePageRequest;
import com.yzcrm.erp.admin.service.AdminFieldService;
import com.yzcrm.erp.admin.service.AdminSceneService;
import com.yzcrm.erp.crm.common.CrmEnum;
import com.yzcrm.erp.crm.common.ProductEnum;
import com.yzcrm.erp.crm.entity.CrmProduct;
import com.yzcrm.erp.psi.entity.PsiProductSpec;
import com.yzcrm.erp.psi.entity.PsiStockpile;
import com.yzcrm.erp.psi.entity.PsiStorehouse;
import com.yzcrm.utils.BaseUtil;
import com.yzcrm.utils.FieldUtil;
import com.yzcrm.utils.R;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class CrmProductService {

    @Inject
    private AdminFieldService adminFieldService;

    @Inject
    private FieldUtil fieldUtil;

    @Inject
    private CrmProductCategoryService crmProductCategoryService;

    @Inject
    private CrmRecordService crmRecordService;

    @Inject
    private AdminSceneService adminSceneService;

    /**
     * 分页条件查询产品
     */
    public Page<Record> queryPage(BasePageRequest<CrmProduct> basePageRequest) {
        return Db.paginate(basePageRequest.getPage(), basePageRequest.getLimit(), Db.getSqlPara("crm.product.getProductPageList"));
    }

    /**
     * 添加或修改产品
     *
     * @param jsonObject
     */
    @Before(TxSerializable.class)
    public R saveAndUpdate(JSONObject jsonObject) {


        CrmProduct crmProduct = jsonObject.getObject("entity", CrmProduct.class);

//        Log.getLog(CrmProductService.class).info(jsonObject.toString() +"..." + crmProduct.getProductType() + "..." +ProductEnum.PRODUCT_TYPE_CRM.getType()  + "..." +ProductEnum.PRODUCT_TYPE_PSI.getType() );

        if(ProductEnum.PRODUCT_TYPE_CRM.getType() != crmProduct.getProductType() &&
                ProductEnum.PRODUCT_TYPE_PSI.getType() != crmProduct.getProductType() &&
                ProductEnum.PRODUCT_TYPE_ALL.getType() != crmProduct.getProductType()) {
            return R.error("产品类型不正确");
        }

        String batchId = StrUtil.isNotEmpty(crmProduct.getBatchId()) ? crmProduct.getBatchId() : IdUtil.simpleUUID();
        crmRecordService.updateRecord(jsonObject.getJSONArray("field"), batchId);
        adminFieldService.save(jsonObject.getJSONArray("field"), batchId);
        if (crmProduct.getProductId() == null) {
            // 增加产品

//            // 名称唯一判断
//            CrmProduct oldProduct = CrmProduct.dao.findFirst(Db.getSqlPara("crm.product.getProductByName",Kv.by("name",crmProduct.getName())));
//            if(ObjectUtil.isNotNull(oldProduct) && oldProduct.getName().equals(crmProduct.getName())) {
//
//                return R.error("已存在相同产品名称的产品");
//            }

            // delete by jiangxue 2020/06/23 有可能存在编号相同的不同产品
//            Integer product = Db.queryInt(Db.getSql("crm.product.getByNum"),crmProduct.getNum());
//            if (product != 0){
//                return R.error("产品编号已存在，请校对后再添加！");
//            }
//            crmProduct.setStatus(jsonObject.getJSONObject("entity").getJSONArray("storehouse_id").toString());
            crmProduct.setStatus(1);
            crmProduct.setCreateUserId(BaseUtil.getUser().getUserId());
            crmProduct.setCreateTime(DateUtil.date());
            crmProduct.setUpdateTime(DateUtil.date());
            crmProduct.setOwnerUserId(BaseUtil.getUser().getUserId().toString());
            crmProduct.setBatchId(batchId);
            crmProduct.setCheckStatus(1); // 暂时不需要审核
            boolean save = crmProduct.save();


            // 仓库产品型号处理
            if(ProductEnum.PRODUCT_TYPE_CRM.getType() == crmProduct.getProductType()) {
                // 客户关系管理

                crmRecordService.addRecord(crmProduct.getProductId(), CrmEnum.CRM_PRODUCT);

            } else if(ProductEnum.PRODUCT_TYPE_PSI.getType() == crmProduct.getProductType() ||
                    ProductEnum.PRODUCT_TYPE_ALL.getType() == crmProduct.getProductType()) {
                // 进销存

                crmRecordService.addRecord(crmProduct.getProductId(), CrmEnum.PSI_PRODUCT);

                // 增加规格和在库
                JSONArray jsonArraySpec = jsonObject.getJSONArray("spec");
                for (int i = 0; i < jsonArraySpec.size(); i++) {

                    JSONObject jsonObjectSpec = jsonArraySpec.getJSONObject(i);
                    PsiProductSpec spec = jsonObjectSpec.toJavaObject(PsiProductSpec.class);


                    Integer count = Db.queryInt("select count(*) as count from yzcrm_psi_product_spec where product_id = ? and num = ? and spec_name = ? and status!=2 ",
                            spec.getProductId(), spec.getNum(), spec.getSpecName());
                    if(count > 0) {
                        throw new YzcrmException("编号，规格有重复。重复编号："+ spec.getNum() +",规格：" + spec.getSpecName());
                    }

                    // 增加规格
                    spec.setCreateTime(DateUtil.date());
                    spec.setCreateUserId(BaseUtil.getUser().getUserId());
                    spec.setUpdateTime(DateUtil.date());
                    spec.setProductId(crmProduct.getProductId());
                    spec.setStatus(1);
                    boolean result = spec.save();
                    if(!result) {
                        throw new YzcrmException("规格增加失败");
                    }

                    // 增加该规格产品的在库
                    List<PsiStockpile> listStockPile = null;
                    if (jsonObjectSpec.getJSONArray("storehouse") != null) {

                        listStockPile = jsonObjectSpec.getJSONArray("storehouse").toJavaList(PsiStockpile.class);
                    } else {
                    }

                    if(ObjectUtil.isNotNull(listStockPile) && listStockPile.size() > 0) {

                        for (int j = 0; j < listStockPile.size(); j++) {

                            PsiStockpile stockpile = listStockPile.get(j);
                            stockpile.setProductSpecId(spec.getProductSpecId());
                            stockpile.setProductId(spec.getProductId());
                            stockpile.setQuantity(0);
                            stockpile.setCreateTime(DateUtil.date());
                            stockpile.setCreateUserId(BaseUtil.getUser().getUserId());
                            stockpile.setUpdateTime(DateUtil.date());
                            stockpile.setStatus(1);
                            result = stockpile.save();

                            if(!result) {
                                throw new YzcrmException("在库数据生成失败");
                            }
                        }

                    } else {

                        // 没有开启预警的情况下增加默认在库
                        String[] listStorehouse = crmProduct.getStorehouseId().split(",");
                        for (int j = 0; j < listStorehouse.length; j++) {

                            Integer storehouseId = Integer.valueOf(listStorehouse[j]);

                            PsiStockpile stockpile = new PsiStockpile();
                            stockpile.setProductSpecId(spec.getProductSpecId());
                            stockpile.setProductId(spec.getProductId());
                            stockpile.setStorehouseId(storehouseId);
                            stockpile.setQuantity(0);
                            stockpile.setMinnumWarn(0);
                            stockpile.setMaxnumWarn(0);
                            stockpile.setCreateTime(DateUtil.date());
                            stockpile.setCreateUserId(BaseUtil.getUser().getUserId());
                            stockpile.setUpdateTime(DateUtil.date());
                            stockpile.setStatus(1);
                            result = stockpile.save();

                            if(!result) {
                                throw new YzcrmException("在库数据生成失败");
                            }
                        }
                    }
                }

            } else {
            }

            return save ? R.ok() : R.error();
        } else {
            // 修改产品
            crmProduct.setCheckStatus(1); // 暂时不需要审核
            crmProduct.setUpdateTime(DateUtil.date());
            crmProduct.setUpdateUserId(BaseUtil.getUser().getUserId());

            boolean result = false;

            // 仓库产品型号处理
            if(ProductEnum.PRODUCT_TYPE_CRM.getType() == crmProduct.getProductType()) {
                // 客户关系管理

                CrmProduct oldCrmProduct = new CrmProduct().dao().findById(crmProduct.getProductId());
                crmRecordService.updateRecord(oldCrmProduct, crmProduct, CrmEnum.CRM_PRODUCT);

            } else if(ProductEnum.PRODUCT_TYPE_PSI.getType() == crmProduct.getProductType() ||
                    ProductEnum.PRODUCT_TYPE_ALL.getType() == crmProduct.getProductType()) {
                // 进销存

                CrmProduct oldCrmProduct = new CrmProduct().dao().findById(crmProduct.getProductId());
                crmRecordService.updateRecord(oldCrmProduct, crmProduct, CrmEnum.PSI_PRODUCT);

//                // 名称唯一判断
//                CrmProduct oldProduct = CrmProduct.dao.findFirst(Db.getSqlPara("crm.product.getProductByName",Kv.by("name",crmProduct.getName())));
//                if(ObjectUtil.isNotNull(oldProduct) && oldProduct.getName().equals(crmProduct.getName())
//                        && oldProduct.getProductId()!=crmProduct.getProductId()) {
//
//                    return R.error("已存在相同产品名称的产品");
//                }

                // 根据产品ID获取原产品规格及在库数量，判断是更新还是被删除
                List<PsiProductSpec> listOldSpec = PsiProductSpec.dao.find(Db.getSql("psi.productSpec.querySpecByProductId"), crmProduct.getProductId());
                for (int i = 0; i < listOldSpec.size(); i++) {

                    PsiProductSpec oldSpec = listOldSpec.get(i);

                    boolean isHave = false;
                    JSONArray jsonArraySpec = jsonObject.getJSONArray("spec");
                    for (int j = 0; j < jsonArraySpec.size(); j++) {
                        JSONObject jsonObjectSpec = jsonArraySpec.getJSONObject(j);
                        PsiProductSpec spec = jsonObjectSpec.toJavaObject(PsiProductSpec.class);

                        if(ObjectUtil.isNotNull(spec.getProductSpecId())
                                && spec.getProductSpecId().equals(oldSpec.getProductSpecId())) {

                            // 编号规格原数据库存在，是修改
                            isHave = true;

                            // 修改处理
                            // 更新编号规格
                            if(oldSpec.getNum().equals(spec.getNum())
                                    && oldSpec.getSpecName().equals(spec.getSpecName())) {
                                // 编号 规格 无变更
                                // 不用更新

                            } else {
                                // 编号 规格 有变更

                                Integer count = Db.queryInt("select count(*) as count from yzcrm_psi_product_spec where product_id = ? and num = ? and spec_name = ? and status!=2 ",
                                        spec.getProductId(), spec.getNum(), spec.getSpecName());
                                if(count > 0) {
                                    throw new YzcrmException("编号，规格有重复。重复编号："+ spec.getNum() +",规格：" + spec.getSpecName());
                                }

                                oldSpec.setNum(spec.getNum());
                                oldSpec.setSpecName(spec.getSpecName());
                                oldSpec.setUpdateTime(DateUtil.date());
                                result = oldSpec.update();
                                if(!result) {
                                    throw new YzcrmException("编号规格更新失败");
                                }

                            }

                            // 更新在库
                            List<PsiStockpile> listOldStockpile = PsiStockpile.dao.find(Db.getSql("psi.stockpile.queryStockpileByProductSpecId"), oldSpec.getProductSpecId());
                            for (int k = 0; k < listOldStockpile.size(); k++) {

                                PsiStockpile oldStockpile = listOldStockpile.get(k);

                                // 在库更新
                                boolean isHava = false;
                                if (jsonObjectSpec.getJSONArray("storehouse") != null) {

                                    List<PsiStockpile> listStockPile = jsonObjectSpec.getJSONArray("storehouse").toJavaList(PsiStockpile.class);
                                    for (int l = 0; l < listStockPile.size(); l++) {

                                        PsiStockpile stockpile = listStockPile.get(l);
                                        if (oldStockpile.getStockpileId().equals(stockpile.getStockpileId())) {

                                            isHava = true;

                                            // 更新
                                            oldStockpile.setUpdateUserId(BaseUtil.getUserId());
                                            oldStockpile.setUpdateTime(DateUtil.date());
                                            oldStockpile.setMinnumWarn(stockpile.getMinnumWarn());
                                            oldStockpile.setMaxnumWarn(stockpile.getMaxnumWarn());
                                            result = oldStockpile.update();
                                            if(!result) {
                                                throw new YzcrmException("在库更新失败");
                                            }


                                            break;
                                        }
                                    }
                                }

                                if(!isHava) {

                                    // 判断仓库是否存在
                                    boolean isExistStorehouse = false;
                                    String[] listStorehouse = crmProduct.getStorehouseId().split(",");
                                    for (int l = 0; l < listStorehouse.length; l++) {

                                        Integer storehouseId = Integer.valueOf(listStorehouse[l]);

                                        if (oldStockpile.getStorehouseId().equals(storehouseId)) {
                                            isExistStorehouse = true;
                                            break;
                                        }
                                    }



                                    if(isExistStorehouse) {
                                        // 如果前端传过来的仓库还存在，说明取消预警，将预警改为0

                                        oldStockpile.setMinnumWarn(0);
                                        oldStockpile.setMaxnumWarn(0);
                                        oldStockpile.setUpdateUserId(BaseUtil.getUser().getUserId());
                                        oldStockpile.setUpdateTime(DateUtil.date());
                                        oldStockpile.update();

                                    } else {
                                        // 如果前端传过来的仓库不存在，证明删除

                                        Integer count = Db.queryInt("select sum(quantity) as count from yzcrm_psi_stockpile where stockpile_id = ? and quantity > 0 and status!=2",
                                                oldStockpile.getStockpileId());
                                        if (ObjectUtil.isNotNull(count) && count > 0) {
                                            // 在库不为0
                                            PsiStorehouse storehouse = PsiStorehouse.dao.findFirst(Db.getSql("psi.storehouse.queryById"), oldStockpile.getStorehouseId());
                                            throw new YzcrmException("有库存，您不能够删除仓库\""+storehouse.getName());
                                        }

                                        // 删除在库
                                        Integer updateRowCount = Db.update(Db.getSql("psi.stockpile.deleteStockpileByStockpileId"), DateUtil.date(), oldStockpile.getStockpileId());
                                        if (updateRowCount <= 0) {
                                            throw new YzcrmException("在库更新失败");
                                        }
                                    }

                                } else {
                                }

                            }

                            // 增加该规格产品的在库
                            List<PsiStockpile> listStockPile = null;
                            if (jsonObjectSpec.getJSONArray("storehouse") != null) {

                                listStockPile = jsonObjectSpec.getJSONArray("storehouse").toJavaList(PsiStockpile.class);
                            } else {
                            }

                            if (ObjectUtil.isNotNull(listStockPile) && listStockPile.size() > 0) {

                                for (int l = 0; l < listStockPile.size(); l++) {

                                    PsiStockpile stockpile = listStockPile.get(l);
                                    if (ObjectUtil.isNull(stockpile.getStockpileId())) {
                                        // 追加在库
                                        stockpile.setProductSpecId(spec.getProductSpecId());
                                        stockpile.setProductId(spec.getProductId());
                                        stockpile.setQuantity(0);
                                        stockpile.setCreateTime(DateUtil.date());
                                        stockpile.setCreateUserId(BaseUtil.getUser().getUserId());
                                        stockpile.setUpdateTime(DateUtil.date());
                                        stockpile.setStatus(1);
                                        result = stockpile.save();
                                        if(!result) {
                                            throw new YzcrmException("在库更新失败");
                                        }
                                    }
                                }
                            } else {

                                // 没有开启预警的情况下增加默认在库
                                String[] listStorehouse = crmProduct.getStorehouseId().split(",");
                                for (int k = 0; k < listStorehouse.length; k++) {

                                    Integer storehouseId = Integer.valueOf(listStorehouse[k]);

                                    PsiStockpile stockpile = new PsiStockpile();
                                    stockpile.setProductSpecId(spec.getProductSpecId());
                                    stockpile.setProductId(spec.getProductId());
                                    stockpile.setStorehouseId(storehouseId);
                                    stockpile.setQuantity(0);
                                    stockpile.setMinnumWarn(0);
                                    stockpile.setMaxnumWarn(0);
                                    stockpile.setCreateTime(DateUtil.date());
                                    stockpile.setCreateUserId(BaseUtil.getUser().getUserId());
                                    stockpile.setUpdateTime(DateUtil.date());
                                    stockpile.setStatus(1);
                                    result = stockpile.save();

                                    if(!result) {
                                        throw new YzcrmException("在库数据生成失败");
                                    }
                                }

                            }

                            break;
                        }

                    }

                    // isHave为false编号规格被删除，在传过来的变更数据中没有找到 并且 现在库数量不为0，提示不能删除该编号和规格的产品
                    if(!isHave) {

                        Integer count = Db.queryInt("select sum(quantity) as count from yzcrm_psi_stockpile where product_spec_id = ? and quantity > 0 and status!=2",
                                oldSpec.getProductSpecId());
                        if (ObjectUtil.isNotNull(count) && count > 0) {
                            // 在库不为0
                            throw new YzcrmException("有库存，您不能够删除它。编号："+ oldSpec.getNum() +",规格：" + oldSpec.getSpecName());
                        }

                        // 删除编号和规格
                        Integer updateRowCount = Db.update("update yzcrm_psi_product_spec set status = 2, update_time=? where product_spec_id=?", DateUtil.date(), oldSpec.getProductSpecId());
                        if (updateRowCount <= 0) {
                            throw new YzcrmException("编号规格更新失败");
                        }

                        // 删除在库
                        updateRowCount = Db.update("update yzcrm_psi_stockpile set status = 2, update_time=? where product_spec_id=?", DateUtil.date(), oldSpec.getProductSpecId());
                        if (updateRowCount <= 0) {
                            throw new YzcrmException("在库更新失败");
                        }
                        
                    } else {

                    }

                }

                // 新增
                JSONArray jsonArraySpec = jsonObject.getJSONArray("spec");
                for (int j = 0; j < jsonArraySpec.size(); j++) {
                    JSONObject jsonObjectSpec = jsonArraySpec.getJSONObject(j);
                    PsiProductSpec newSpec = jsonObjectSpec.toJavaObject(PsiProductSpec.class);

                    if(ObjectUtil.isNull(newSpec.getProductSpecId())) {
                        // 新增 同正常追加逻辑

                        // 增加规格
                        newSpec.setCreateTime(DateUtil.date());
                        newSpec.setCreateUserId(BaseUtil.getUser().getUserId());
                        newSpec.setUpdateTime(DateUtil.date());
                        newSpec.setProductId(oldCrmProduct.getProductId());
                        newSpec.setStatus(1);
                        result = newSpec.save();
                        if(!result) {
                            throw new YzcrmException("编号规格更新失败");
                        }

                        // 增加该规格产品的在库
                        List<PsiStockpile> listStockPile = null;
                        if (jsonObjectSpec.getJSONArray("storehouse") != null) {

                            listStockPile = jsonObjectSpec.getJSONArray("storehouse").toJavaList(PsiStockpile.class);
                        } else {
                        }

                        if (ObjectUtil.isNotNull(listStockPile) && listStockPile.size() > 0) {

                            for (int i = 0; i < listStockPile.size(); i++) {

                                PsiStockpile stockpile = listStockPile.get(j);
                                stockpile.setProductSpecId(newSpec.getProductSpecId());
                                stockpile.setProductId(newSpec.getProductId());
                                stockpile.setQuantity(0);
                                stockpile.setCreateTime(DateUtil.date());
                                stockpile.setCreateUserId(BaseUtil.getUser().getUserId());
                                stockpile.setUpdateTime(DateUtil.date());
                                stockpile.setStatus(1);
                                result = stockpile.save();
                                if(!result) {
                                    throw new YzcrmException("在库更新失败");
                                }

                            }
                        } else {

                            // 没有开启预警的情况下增加默认在库
                            String[] listStorehouse = crmProduct.getStorehouseId().split(",");
                            for (int i = 0; i < listStorehouse.length; i++) {

                                Integer storehouseId = Integer.valueOf(listStorehouse[i]);

                                PsiStockpile stockpile = new PsiStockpile();
                                stockpile.setProductSpecId(newSpec.getProductSpecId());
                                stockpile.setProductId(newSpec.getProductId());
                                stockpile.setStorehouseId(storehouseId);
                                stockpile.setQuantity(0);
                                stockpile.setMinnumWarn(0);
                                stockpile.setMaxnumWarn(0);
                                stockpile.setCreateTime(DateUtil.date());
                                stockpile.setCreateUserId(BaseUtil.getUser().getUserId());
                                stockpile.setUpdateTime(DateUtil.date());
                                stockpile.setStatus(1);
                                result = stockpile.save();

                                if(!result) {
                                    throw new YzcrmException("在库数据生成失败");
                                }
                            }
                        }

                    }
                }

            } else {
            }
        }

        return crmProduct.update() ? R.ok() : R.error();
    }

    /**
     * 根据id查询产品
     */
    public Record queryById(Integer id) {
        Record crmProduct = Db.findFirst(Db.getSql("crm.product.queryById"),id);
        List<Record> recordList = Db.find("select name,value from `yzcrm_admin_fieldv` where batch_id = ?", crmProduct.getStr("batch_id"));
        recordList.forEach(field->crmProduct.set(field.getStr("name"),field.getStr("value")));
        return crmProduct;
    }

    /**
     * 根据id查询产品基本信息
     */
    public List<Record> information(Integer id, Integer label) {

        CrmEnum crmEnum = CrmEnum.parse(label);

        Record record = queryById(id);
        List<String> keyList = Arrays.asList("name", "num","price","description", "images", "file", "product_type", "material_category", "check_status", "name_en"
        ,"cost_price_no_tax","cost_price_tax","settlement_price_no_tax","settlement_price_tax","director_price_tax","sales_price_tax");
        List<Record> recordList = adminFieldService.queryInformation(crmEnum,record, keyList);
//        recordList.add(new Record().set("name","产品类型").set("value",new Record().set("catego?ryId",record.getInt("category_id")).set("categoryName",record.getStr("categoryName"))).set("formType","category").set("field_type",1));

        return recordList.stream().sorted(Comparator.comparingInt(r->-r.getInt("field_type"))).map(r-> r.remove("field_type","field_name","setting","type")).collect(Collectors.toList());
    }


    /**
     * 根据产品ID获取规格及在库信息
     * @param productId
     * @return
     */
    public List<Record> listSpecByProductId(Integer productId) {

        // 检索规格
        List<Record> listSpec = Db.find(Db.getSql("psi.productSpec.querySpecByProductId"), productId);

        // 检索在库
        listSpec.forEach(spec ->{

            List<Record> listStockpile = Db.find(Db.getSql("psi.stockpile.queryStockpileByProductSpecId"), spec.getInt("product_spec_id"));

            spec.set("storehouse", listStockpile);
        });

        return listSpec;
    }


    /**
     * 根据id列表删除产品
     */
    @Before(TxSerializable.class)
    public R deleteByIds(String productIds) {
        List<String> ids=StrUtil.splitTrim(productIds,",");
        for (String id : ids) {
            CrmProduct product = CrmProduct.dao.findById(id);
            if (product != null) {

                // 判断是否有在库，如果有在库将不能删除
                Integer count = Db.queryInt("select sum(quantity) as count from yzcrm_psi_stockpile where product_id = ? and quantity > 0 and status!=2",
                        product.getProductId());
                if (ObjectUtil.isNotNull(count) && count > 0) {
                    // 在库不为0
                    throw new YzcrmException("该产品有库存，您不能够删除它。 产品名称："+ product.getName());
                }

//                Db.delete("delete FROM yzcrm_admin_fieldv where batch_id = ?",product.getBatchId());
                product.setStatus(3);
                product.update();
            }
        }
        return R.ok();
    }

    /**
     * 上架或者下架
     */
    public R updateStatus(String ids, Integer status) {
        List<Record> recordList = Db.find("select batch_id from yzcrm_crm_product where  product_id in (" + ids + ")");
        StringBuilder batchIds = new StringBuilder();
        for (Record record : recordList) {
            if (batchIds.length() == 0) {
                batchIds.append("'").append(record.getStr("batch_id")).append("'");
            } else {
                batchIds.append(",'").append(record.getStr("batch_id")).append("'");
            }
        }
        String a;
        if (status == 0) {
            a = "下架";
        } else {
            a = "上架";
        }
        StringBuilder sqlfield = new StringBuilder("update yzcrm_admin_fieldv set value = '" + a + "' where name = '是否上下架' and batch_id in ( ");
        sqlfield.append(batchIds.toString());
        sqlfield.append(" )");
        int f = Db.update(sqlfield.toString());
        return R.isSuccess(f > 0);
    }

    /**
     * @author wyq
     * 查询编辑字段
     */
    public List<Record> queryField(Integer productId, Integer label) {

        CrmEnum crmEnum = CrmEnum.parse(label);

        Record product = queryById(productId);
        List<Integer> list = crmProductCategoryService.queryId(null, product.getInt("category_id"));
        Integer[] categoryIds = new Integer[list.size()];
        categoryIds = list.toArray(categoryIds);
        product.set("category_id",categoryIds);

//        if(label == ProductEnum.PRODUCT_TYPE_PSI.getType()) {
//            // 进销存产品的仓库
//            List<Record> listStorehouse = new ArrayList<>();
//            Record storehouse = new Record();
//            listStorehouse.add(storehouse.set("storehouse_id", product.getInt("storehouse_id")).set("storehouse_name", product.getStr("storehouse_name")));
//            product.set("storehouse_id", listStorehouse);
//        }

        return adminFieldService.queryUpdateField(crmEnum.getType(),product);
    }

    /**
     * @author wyq
     * 获取产品导入查重字段
     */
    public R getCheckingField(){
        return R.ok().put("data","产品名称");
    }
    /**
     * @author zxy
     * 获取上架商品
     */
    public R queryByStatus(BasePageRequest<CrmProduct> basePageRequest) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.fluentPut("status",new JSONObject().fluentPut("name","status").fluentPut("condition","is").fluentPut("value","1"));
        basePageRequest.setJsonObject(jsonObject);
        return adminSceneService.getCrmPageList(basePageRequest);
    }

    /**
     * 查询进销存在库商品
     * @param productId
     * @param productName
     * @param productStatus
     * @param productNameEn
     * @param productNum
     * @param productSpecName
     * @param storehouseId
     * @param storehouseCode
     * @param storehouseName
     * @param productBatchId
     * @param productUpcCode
     * @return
     */
    public List<Record> queryStockpile(Integer productId,
                            String productName,
                            Integer productStatus,
                            String productNameEn,
                            String productNum,
                            String productSpecName,
                            Integer storehouseId,
                            String storehouseCode,
                            String storehouseName,
                            String productBatchId,
                            String productUpcCode,
                            Integer label){

        List<Record> records;

        // 获取入库
        records = Db.find(Db.getSqlPara("crm.product.queryStockpile",
                Kv.by("productName", productName).set("productId", productId).set("productStatus", productStatus)
                        .set("productNameEn", productNameEn).set("productNum", productNum).set("productSpecName", productSpecName)
                        .set("storehouseId", storehouseId).set("storehouseCode", storehouseCode).set("storehouseName", storehouseName)
                        .set("productBatchId", productBatchId).set("productUpcCode", productUpcCode)));

//        if(ObjectUtil.isNotNull(label) &&
//            label.equals(CrmEnum.PSI_PURCHASE_ENTER.getType())) {
//
//            records = Db.find(Db.getSqlPara("crm.product.queryStockpilePurchaseEnter",
//                    Kv.by("productName", productName).set("productId", productId).set("productStatus", productStatus)
//                            .set("productNameEn", productNameEn).set("productNum", productNum).set("productSpecName", productSpecName)
//                            .set("storehouseId", storehouseId).set("storehouseCode", storehouseCode).set("storehouseName", storehouseName)
//                            .set("productBatchId", productBatchId).set("productUpcCode", productUpcCode)));
//
//        } else {
//            records = Db.find(Db.getSqlPara("crm.product.queryStockpile",
//                    Kv.by("productName", productName).set("productId", productId).set("productStatus", productStatus)
//                            .set("productNameEn", productNameEn).set("productNum", productNum).set("productSpecName", productSpecName)
//                            .set("storehouseId", storehouseId).set("storehouseCode", storehouseCode).set("storehouseName", storehouseName)
//                            .set("productBatchId", productBatchId).set("productUpcCode", productUpcCode)));
//        }

        return records;

    }
}
